﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace GENERIC.MVVM.Model
{
    /// <summary>
    /// Editable modèle
    /// </summary>
    /// <typeparam name="TModel">Type du modèle</typeparam>
    public class EditableModel<TModel> : IEditableObject where TModel : ModelBase
    {
        #region Fields

        private Memento<TModel> memento;
        private TModel target;

        #endregion

        #region Constructor

        /// <summary>
        /// Initialise une nouvelle instance de la classe EditableModel
        /// </summary>
        /// <param name="target">Modèle</param>
        public EditableModel(TModel target)
        {
            this.Target = target;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Obtient Le modèle
        /// </summary>
        public TModel Target
        {
            get
            {
                return this.target;
            }
            protected set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("Target", "Target cannot be null");
                }

                if (Object.ReferenceEquals(this.Target, value))
                    return;

                this.target = value;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Commencer l'édition
        /// </summary>
        public void BeginEdit()
        {
            if (this.memento == null)
                this.memento = new Memento<TModel>(Target);
        }

        /// <summary>
        /// Annuler l'édition
        /// </summary>
        public void CancelEdit()
        {
            if (this.memento == null)
                throw new ArgumentNullException("Memento", "BeginEdit() is not invoked");

            this.memento.Restore(Target);
            this.memento = null;
        }

        /// <summary>
        /// Fianliser l'édition
        /// </summary>
        public void EndEdit()
        {
            if (this.memento == null)
                throw new ArgumentNullException("Memento", "BeginEdit() is not invoked");

            this.memento = null;
        }

        #endregion
    }
}
